package cn.iocoder.yudao.module.shop.service.orderfeedback;

import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletDO;
import cn.iocoder.yudao.module.pay.service.wallet.PayWalletService;
import cn.iocoder.yudao.module.shop.dal.dataobject.item.ShopItemDO;
import cn.iocoder.yudao.module.shop.dal.dataobject.order.ShopOrderDO;
import cn.iocoder.yudao.module.shop.dal.dataobject.order.ShopOrderItemDO;
import cn.iocoder.yudao.module.shop.service.item.ShopItemService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.tenantdetail.TenantDetailDO;
import cn.iocoder.yudao.module.system.service.tenantdetail.TenantDetailService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.iocoder.yudao.module.shop.controller.admin.orderfeedback.vo.*;
import cn.iocoder.yudao.module.shop.dal.dataobject.orderfeedback.ShopOrderFeedbackDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.shop.convert.orderfeedback.ShopOrderFeedbackConvert;
import cn.iocoder.yudao.module.shop.dal.mysql.orderfeedback.ShopOrderFeedbackMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.shop.enums.ErrorCodeConstants.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.iocoder.yudao.module.shop.config.OrderFeedbackConfig;

/**
 * 顾客订单反馈 Service 实现类
 *
 * @author 曹建伟
 */
@Service
@Validated
public class ShopOrderFeedbackServiceImpl implements ShopOrderFeedbackService {

    @Resource
    private ShopOrderFeedbackMapper orderFeedbackMapper;

    @Resource
    private MemberUserApi memberUserApi;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private TenantDetailService tenantDetailService;

    @Resource
    private PayWalletService payWalletService;

    @Resource
    private ShopItemService shopItemService;

    @Override
    public Long createOrderFeedback(ShopOrderFeedbackCreateReqVO createReqVO) {
        // 插入
        ShopOrderFeedbackDO orderFeedback = ShopOrderFeedbackConvert.INSTANCE.convert(createReqVO);
        orderFeedbackMapper.insert(orderFeedback);
        // 返回
        return orderFeedback.getId();
    }

    @Override
    public void updateOrderFeedback(ShopOrderFeedbackUpdateReqVO updateReqVO) {
        // 校验存在
        validateOrderFeedbackExists(updateReqVO.getId());
        // 更新
        ShopOrderFeedbackDO updateObj = ShopOrderFeedbackConvert.INSTANCE.convert(updateReqVO);
        orderFeedbackMapper.updateById(updateObj);
    }

    @Override
    public void deleteOrderFeedback(Long id) {
        // 校验存在
        validateOrderFeedbackExists(id);
        // 删除
        orderFeedbackMapper.deleteById(id);
    }

    private void validateOrderFeedbackExists(Long id) {
        if (orderFeedbackMapper.selectById(id) == null) {
            throw exception(ORDER_FEEDBACK_NOT_EXISTS);
        }
    }

    @Override
    public ShopOrderFeedbackDO getOrderFeedback(Long id) {
        return orderFeedbackMapper.selectById(id);
    }

    @Override
    public List<ShopOrderFeedbackDO> getOrderFeedbackList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return orderFeedbackMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<ShopOrderFeedbackDO> getOrderFeedbackPage(ShopOrderFeedbackPageReqVO pageReqVO) {
        return orderFeedbackMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ShopOrderFeedbackDO> getOrderFeedbackList(ShopOrderFeedbackExportReqVO exportReqVO) {
        return orderFeedbackMapper.selectList(exportReqVO);
    }

    @Override
    public ShopOrderFeedbackDO getByOrderId(Long orderId){
        return orderFeedbackMapper.selectOne(ShopOrderFeedbackDO::getOrderId, orderId);
    }

    @Override
    public List<ShopOrderFeedbackDO> getListbyOrderId(Collection<Long> orderIds){
        if(orderIds.isEmpty()){
            return new ArrayList<>();
        }
        return orderFeedbackMapper.selectList(ShopOrderFeedbackDO::getOrderId, orderIds);
    }

    @Override
    public Boolean rollback(ShopOrderDO order){
        ShopOrderFeedbackDO feedbackDO = orderFeedbackMapper.selectOne(ShopOrderFeedbackDO::getOrderId, order.getId());
        if(feedbackDO == null){
            return true;
        }

        orderFeedbackMapper.deleteById(feedbackDO);

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ShopOrderFeedbackDO createByOrder(ShopOrderDO shopOrderDO, List<ShopOrderItemDO> orderItemDOList){
        ShopOrderFeedbackDO feedbackDO = orderFeedbackMapper.selectOne(ShopOrderFeedbackDO::getOrderId, shopOrderDO.getId());
        if(feedbackDO == null){
            feedbackDO = new ShopOrderFeedbackDO();

            MemberUserRespDTO member = memberUserApi.getUser(shopOrderDO.getMemberId());
            if(member == null){
                throw exception(ORDER_FEEDBACK_NOT_FIND_MEMBER);
            }

            AdminUserRespDTO master = adminUserApi.getUser(shopOrderDO.getUserId());
            if(master == null){
                throw exception(ORDER_FEEDBACK_NOT_FIND_MASTER);
            }

            TenantDetailDO tenantDetailDO = tenantDetailService.getTenantDetailByTenantId(shopOrderDO.getTenantId());
            if(tenantDetailDO == null){
                throw exception(ORDER_FEEDBACK_NOT_FIND_TENANT);
            }

            PayWalletDO walletDO = payWalletService.getWallet(shopOrderDO.getMemberId(), UserTypeEnum.MEMBER.getValue());
            Integer balance = 0;
            if(walletDO != null){
                balance = walletDO.getBalance();
            }

            feedbackDO.setOrderId(shopOrderDO.getId());
            feedbackDO.setStartTime(shopOrderDO.getStartTime());
            Integer payType = 0;
            if(shopOrderDO.getWalletCharge()){
                payType = 0;            //余额支付
            }else if(shopOrderDO.getTimesCharge()){
                payType = 2;            //次数支付
            }else{
                payType = 1;            //现金支付
            }

            if(orderItemDOList.size() > 0){
                ShopItemDO itemDO = shopItemService.getItem(orderItemDOList.get(0).getOptItemId());
                if(itemDO == null){
                    throw exception(ORDER_FEEDBACK_NOT_FIND_SHOP_ITEM);
                }

                feedbackDO.setItemName(itemDO.getName());
            }else{
                feedbackDO.setItemName("服务项目");
            }

            feedbackDO.setPayType(payType);
            feedbackDO.setPayPrice(shopOrderDO.getPayPrice());
            feedbackDO.setBalance(balance);

            feedbackDO.setMemberId(shopOrderDO.getMemberId());
            feedbackDO.setMemberName(member.getNickname());

            feedbackDO.setMasterId(master.getId());
            feedbackDO.setMasterName(master.getNickname());
            feedbackDO.setMasterAvatar(master.getAvatar());

            feedbackDO.setTenantId(shopOrderDO.getTenantId());
            feedbackDO.setTenantName(tenantDetailDO.getName());
            feedbackDO.setTenantPic(tenantDetailDO.getTitleUrl());

            feedbackDO.setBalanceScore(OrderFeedbackConfig.balanceScore);
            feedbackDO.setSkillScore(OrderFeedbackConfig.skillScore);
            feedbackDO.setServiceScore(OrderFeedbackConfig.serviceScore);
            feedbackDO.setResultScore(OrderFeedbackConfig.resultScore);
            feedbackDO.setMsg("");

            feedbackDO.setConfirmed(false);

            orderFeedbackMapper.insert(feedbackDO);
        }

        return feedbackDO;
    }

    @Override
    public ShopOrderFeedbackDO confirm(@Valid ShopOrderFeedbackUpdateReqVO updateReqVO){
        // 校验存在
        validateOrderFeedbackExists(updateReqVO.getId());
        // 更新
        ShopOrderFeedbackDO updateObj = ShopOrderFeedbackConvert.INSTANCE.convert(updateReqVO);
        updateObj.setConfirmed(true);

        orderFeedbackMapper.updateById(updateObj);

        return orderFeedbackMapper.selectById(updateReqVO.getId());
    }

}
